package org.red_cross_service.service;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Paths;

@Slf4j
@Service
public class AsyncService {

    @SneakyThrows
    @Async
    public void asyncMethod(String inputFilePath, String outputFilePath, String fileUploadDir) {
        // 设置输出文件路径

        // 构建 ffmpeg 命令
        String[] commandArray = {
                "ffmpeg",
                "-y",
                "-i", inputFilePath,
                "-c:v", "libx264", // 使用 libx264 编码视频
                "-c:a", "aac",     // 使用 AAC 编码音频
                "-start_number", "0",
                "-hls_time", "5",
                "-hls_list_size", "0",
                "-f", "hls",
                outputFilePath
        };

        // 执行 ffmpeg 命令
        log.info("开始执行 ffmpeg 命令: {}", String.join(" ", commandArray));
        ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
        processBuilder.directory(new File(fileUploadDir));
        processBuilder.redirectErrorStream(true); // 合并错误流和标准输出流
        Process process = processBuilder.start();

        // 读取输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            log.info(line);
        }

        // 检查退出码
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("ffmpeg 执行失败，退出码: " + exitCode);
        }

        log.info("ffmpeg 执行完成，输出文件: {}", outputFilePath);
    }

}
